import { router, addRoutes } from "./router";
import { getToken } from "./composables/auth";
import { showFullLoading, hideFullLoading } from "./composables/util";
import store from "./store";
//全局前置路由守卫
router.beforeEach(async (to, from, next) => {
  // 显示loading
  showFullLoading();
  const token = getToken();
  // 没有登录，强制跳转回登录页
  if (!token && to.path != "/login") {
    //可以添加提示
    return next({ path: "/login" });
  }
  // 防止重复登录
  if (!token && to.path != "/login") {
    return next({ path: "/login" });
  }
  // 如果用户登录了，自动获取用户信息，并存储在vuex当中
  if (token) {
    await store.dispatch("getinfo");
  }
  let hasNewRoutes = false;
  if (token) {
    let { menus } = await store.dispatch("getinfo");
    //动态添加路由
    hasNewRoutes = addRoutes(menus);
  }
  //设置页面标题
  let title = (to.meta.title ? to.meta.title : "") + "-我要把这个网站写完";
  document.title = title;
  hasNewRoutes ? next(to.fullPath) : next();
});
// 全局后置守卫
router.afterEach((to, from) => hideFullLoading());
